<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="24">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input class="input-item" v-model="ruleForm.taskName" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设置截至时间" prop="endDate">
              <el-date-picker v-model="ruleForm.endDate" type="date" placeholder="选择日期"
                              format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行人" prop="executor">
              <el-select v-model="ruleForm.executor" placeholder="请选择" filterable>
                <el-option v-for="item in listUsers" :key="item.userId"
                           :label="item.showName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参与人">
              <el-select v-model="ruleForm.listParticipants" filterable multiple collapse-tags placeholder="请选择">
                <el-option v-for="item in listUsers" :key="item.userId"
                           :label="item.showName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作流程" prop="flowId">
              <el-select v-model="ruleForm.flowId" placeholder="请选择" @change="flowEntryChange">
                <el-option v-for="(item,index) in flowEntrylist" :key="index"
                           :label="item.flowName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核进度">
              <ProcessViewer ref="ProcessViewers" :style="{height: (getMainContextHeight - 500) + 'px'}"
                             :xml="processXml"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务描述">
              <el-input type="textarea" class="input-item" rows="4" v-model="ruleForm.taskDesc" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务日志">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :timestamp="activity.createTime">
                  {{activity.userName}}：{{activity.content}}
                </el-timeline-item>
              </el-timeline>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button @click="onCancel(false)">取消</el-button>
              <el-button type="danger" @click="handleDelete()" v-if="tasksId">删除</el-button>
              <el-button type="primary" @click="submitForm()">确定</el-button>
              <el-button type="primary" @click="submitOver()" v-if="submitbtn">提交完成</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import '@/views/workflow/package/theme/index.scss';
import { BusinessOpportunities } from '@/api/commercial.js';
import ProcessViewer from '@/views/workflow/components/ProcessViewer.vue';
import { mapGetters } from 'vuex';
import { BusinessFlow, Administration } from '@/api/projectAdministration.js';
import TasksComplete from './CommercialTaskComplete.vue';
export default {
  name: 'CommercialTaskAdd',
  components: { ProcessViewer },
  props: {
    tasksId: {
      default: undefined
    },
    businessType: {
      default: undefined
    },
    oppoId: {
      default: undefined
    }
  },
  data () {
    return {
      loading: false,
      isShowloading: false,
      submitbtn: false,
      processXml: undefined,
      listUsers: [],
      customerlist: [],
      flowEntrylist: [],
      situation: 1,
      activities: [],
      ruleForm: {
        taskName: '',
        endDate: '',
        executor: '',
        participants: '',
        flowId: '',
        taskDesc: ''
      },
      rules: {
        taskName: [{ required: true, message: '请输入', trigger: 'blur' }],
        endDate: [{ required: true, message: '请选择', trigger: 'change' }],
        executor: [{ required: true, message: '请选择', trigger: 'blur' }],
        participants: [{ required: true, message: '请选择', trigger: 'blur' }],
        flowId: [{ required: true, message: '请选择', trigger: 'change' }],
        taskDesc: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  created () {
  },
  computed: {
    isEdit () {
      return this.tasksId != null && this.tasksId !== '';
    },
    ...mapGetters(['getMainContextHeight'])
  },
  mounted () {
    this.listGroupUser()
    this.loadflowWidgetData()
    if (this.isEdit) {
      this.submitbtn = true
      this.loadWorkflowDetail()
      this.loadTasklogWidgetData()
    }
  },
  methods: {
    /**
     * 任务详情
     */
    loadWorkflowDetail () {
      let params = {
        id: this.tasksId
      }
      return new Promise((resolve, reject) => {
        BusinessOpportunities.Taskdetail(this, params).then(res => {
          this.ruleForm = res.data
          this.processXml = res.data.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
          let participantsVoList = res.data.listParticipants
          if (participantsVoList) {
            participantsVoList.forEach((item, index) => {
              this.ruleForm.participants.push(item.userId)
            })
          }
          this.loadflowWidgetData();
          this.$forceUpdate();
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 任务日志
     */
    loadTasklogWidgetData () {
      let params = {
        taskId: this.tasksId,
        logType: 1
      };
      return new Promise((resolve, reject) => {
        Administration.tasklog(this, params).then(res => {
          this.activities = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 审核流程列表
     */
    loadflowWidgetData () {
      let params = {
        businessStage: 1,
        businessType: this.$route.query.businessType ? this.$route.query.businessType : this.businessType
      }
      return new Promise((resolve, reject) => {
        BusinessFlow.lists(this, params).then(res => {
          this.flowEntrylist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 审核流程选择
     */
    flowEntryChange (value) {
      this.flowEntrylist.forEach(item => {
        if (item.id === value) {
          this.processXml = item.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
        }
      })
    },
    /**
     * 人员列表
     */
    listGroupUser () {
      let params = this.$route.query.oppoId;
      return new Promise((resolve, reject) => {
        BusinessOpportunities.detail(this, params).then(res => {
          this.listUsers = res.data.oppoUserList
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 提交表单
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          this.ruleForm.opportunityId = this.$route.query.oppoId ? this.$route.query.oppoId : this.oppoId
          let params = {
            opportunityTaskDto: this.ruleForm
          };
          if (this.isEdit) { // 修改
            params = {
              opportunityTaskUpdateDto: this.ruleForm
            }
            return new Promise((resolve, reject) => {
              BusinessOpportunities.Taskupdate(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            return new Promise((resolve, reject) => {
              BusinessOpportunities.Taskadd(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 提交完成
    submitOver () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let params = {
            tasksId: this.tasksId
          };
          this.$dialog.show('任务完成', TasksComplete, {
            area: '600px'
          }, params).then(res => {
            this.subComplete(res)
          }).catch(e => {});
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 提交完成
    subComplete (data) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let params = {
            taskId: this.tasksId,
            flowId: this.ruleForm.flowId,
            ...data
          }
          return new Promise((resolve, reject) => {
            BusinessOpportunities.taskcomplete(this, params).then(res => {
              this.$message.success('提交完成！');
              this.onCancel(true);
            }).catch(e => {
              reject(e);
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 删除
    handleDelete () {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          id: this.tasksId
        }
        return new Promise((resolve, reject) => {
          BusinessOpportunities.Taskdelete(this, params).then(res => {
            this.$message.success('删除成功！');
            this.onCancel(true);
          }).catch(e => {
            reject(e);
          });
        });
      })
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
  h4{margin-bottom: 0;}
  .table_container{margin: 10px 0;}
  .form-single-info{display: flex;justify-content: center;}
  .el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
  .el-form-info strong{margin: 0 10px;}
</style>
<style>
  .el-select{overflow: hidden;}
  .el-select .el-select__tags > span{display: flex !important;}
</style>
